# -*- coding:UTF-8 -*-

import random
import requests
import time


from spider_xue.account import set_account_use_not
from db import *
from spider_xue.ip import headers_list
from spider_xue.logger import logging
from spider_xue.new_ip import new_ip_obj
from spider_xue.settings import INFO, ERROR, URL1, URL5, refresh_session_count, HEADERS
from spider_xue.utils import send_msg


class Snowball():
    # 构造函数
    def __init__(self, func=None):
        self.session = requests.Session()
        self.mainURL = URL1.format(
            "SH600096", str(int(time.time())) + "000", 142)
        self.func = func
        self.headers = HEADERS

    def refresh_session(self, cookie):
        for i in range(refresh_session_count):
            try:
                iipp = new_ip_obj.get_one()
                if not iipp:
                    send_msg("ip 用完了！！！！！！")
                    return False, 0
                # cookie = "xq_a_token=a6e746ce0d133a885cd1932debc192998c0f4dae; xqat=a6e746ce0d133a885cd1932debc192998c0f4dae; xq_r_token=d56ed16c62b73e8810c19ec04afc4e1602254687; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTYzMzI4MjI3OCwiY3RtIjoxNjMxOTcyNjI1MDg1LCJjaWQiOiJkOWQwbjRBWnVwIn0.jnmphDsdDj7yKzhimRY4IhLLYe-tUKBe8qfGm0R0zxdYQgq1ewHC0jc6islMgOoIN50FweL7r3WtKoBNy8131k3mInQPJtSFAZD4SgfERf7g_BOORkAV_xNrTVnfPVZVfYL_iUrX9Z27sl8YKoyUheb_ju0uy7HhqgqDs4Wo_rfitWyBF6XLFo6IiPQv7Sj0z-Z7oH5s8WK2cR-wdouG50Qndt9uaRL3ussTzB28Kr7uvVqPku2JayldveVTcmmCwf7_sqXlRmy8ga3rmbFYXWGu83pHslzsA2YiCyjWas0RTGtBK6hUWihxyXpMbxlKFb9FcFQcPsHHEtel64ltTg; u=841631972660100; Hm_lvt_1db88642e346389874251b5a1eded6e3=1631972661; device_id=ab50a06cfa55115d7cf73dbf17c21d76; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1631972668; is_overseas=0"
                self.headers['user-agent'] = random.choice(headers_list)
                self.headers['cookie'] = cookie
                self.session.headers = self.headers
                self.session.proxies = {"http": "http://{}".format(iipp["ip"])}
                res = self.session.get(self.mainURL, timeout=5)
                if res.status_code == 200:
                    logging.info(f"重新选取代理IP成功！ {iipp['ip']}")
                    return True, iipp['ip']
                else:
                    new_ip_obj.delete_one(iipp)
                    logging.info(f"选取的代理IP不可用 {iipp['ip']}")
            except Exception as e:
                if iipp:
                    new_ip_obj.delete_one(iipp)
                logging.info(f"Ip bug........... {str(e)} ")

        return False, 0

    def refresh_session_queue(self, cookie, workQueueIP):
        for i in range(refresh_session_count):
            try:
                iipp = workQueueIP.get()
                if not iipp:
                    send_msg("ip 用完了！！！！！！")
                    return False, 0
                # cookie = "xq_a_token=a6e746ce0d133a885cd1932debc192998c0f4dae; xqat=a6e746ce0d133a885cd1932debc192998c0f4dae; xq_r_token=d56ed16c62b73e8810c19ec04afc4e1602254687; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTYzMzI4MjI3OCwiY3RtIjoxNjMxOTcyNjI1MDg1LCJjaWQiOiJkOWQwbjRBWnVwIn0.jnmphDsdDj7yKzhimRY4IhLLYe-tUKBe8qfGm0R0zxdYQgq1ewHC0jc6islMgOoIN50FweL7r3WtKoBNy8131k3mInQPJtSFAZD4SgfERf7g_BOORkAV_xNrTVnfPVZVfYL_iUrX9Z27sl8YKoyUheb_ju0uy7HhqgqDs4Wo_rfitWyBF6XLFo6IiPQv7Sj0z-Z7oH5s8WK2cR-wdouG50Qndt9uaRL3ussTzB28Kr7uvVqPku2JayldveVTcmmCwf7_sqXlRmy8ga3rmbFYXWGu83pHslzsA2YiCyjWas0RTGtBK6hUWihxyXpMbxlKFb9FcFQcPsHHEtel64ltTg; u=841631972660100; Hm_lvt_1db88642e346389874251b5a1eded6e3=1631972661; device_id=ab50a06cfa55115d7cf73dbf17c21d76; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1631972668; is_overseas=0"
                self.headers['user-agent'] = random.choice(headers_list)
                self.headers['cookie'] = cookie
                self.session.headers = self.headers
                self.session.proxies = {"http": "http://{}".format(iipp["ip"])}
                res = self.session.get(self.mainURL, timeout=5)
                if res.status_code == 200:
                    logging.info(f"重新选取代理IP成功！ {iipp['ip']}")
                    return True, iipp['ip']
                else:
                    new_ip_obj.delete_one(iipp)
                    logging.info(f"选取的代理IP不可用 {iipp['ip']}")

            except Exception as e:
                if iipp:
                    new_ip_obj.delete_one(iipp)
                err = str(e) if 'HTTPConnectionPool' not in str(
                    e) else "HTTPConnectionPool problem"
                logging.info(f"Ip bug........... {err} {iipp['ip']}")

        return False, 0

    def get_res_together(self, urrl, stock, start, end, ddbb, timestamp, timeout=3):
        html = self.session.get(urrl.format(
            stock['symbol'], start, end), timeout=timeout)
        if html.status_code != 200:
            return 0
        tempJson = html.json()
        data = tempJson.get('data')
        if not data or data['symbol'] != stock['symbol']:
            return 0
        ddbb.update_one({'symbol': data['symbol']}, {
                        "$set": {"item": data['item']}}, upsert=True)
        if self.func:

            self.func(data, stock, timestamp)

        return 1
    
    def get_res_together_no_save(self, urrl, stock, start, end, ddbb, timestamp, timeout=3):
        html = self.session.get(urrl.format(
            stock['symbol'], start, end), timeout=timeout)
        if html.status_code != 200:
            return 0
        try:
            tempJson = html.json()
        except:
            return 0
        data = tempJson.get('data')
        if not data or data['symbol'] != stock['symbol']:
            return 0
        ddbb.update_one({'symbol': data['symbol']}, {
                        "$set": {"item": data['item']}}, upsert=True)
        if self.func:

            self.func(data, stock, timestamp)

        return 1

    def insert(self, data):
        data_one_db.insert_many(data)


if __name__ == "__main__":
    pass
